import React from 'react';
import { createRoot } from 'react-dom/client';
import './index.css';
import { CloseIcon } from '@/components/icons';

type TModalProps = {
   isOpen: boolean;
   onClose?: () => void;
   showClose?: boolean;
   header?: React.ReactNode;
   content?: React.ReactNode;
   children?: React.ReactNode;
   footer?: React.ReactNode;
};

const Modal = ({
   isOpen,
   onClose,
   showClose = false,
   header,
   content,
   children = null,
   footer,
}: TModalProps) => {
   if (!isOpen) return null;

   return (
      <div className="modal-overlay">
         <div className="modal">
            {showClose && (
               <CloseIcon
                  type="white"
                  className="absolute right-0 -top-9"
                  onClick={onClose}
               />
            )}

            {header && <div className="modal-header">{header}</div>}
            {content && <div className="modal-content">{content}</div>}
            {children && <div className="modal-content">{children}</div>}
            {footer && <div className="modal-footer">{footer}</div>}
         </div>
      </div>
   );
};

Modal.confirm = ({ onOk, title = '', content = '' }) => {
   const modelEle = document.createElement('div');
   const root = document.getElementById('root');
   root.appendChild(modelEle);

   const modalRoot = createRoot(modelEle);

   const handleClose = () => {
      modalRoot.unmount();
      root.removeChild(modelEle);
   };

   const handleOk = () => {
      onOk();
      handleClose();
   };

   modalRoot.render(
      <Modal
         isOpen={true}
         onClose={handleClose}
         header={title}
         children={content}
         footer={[
            <div className="color-disabled" onClick={handleClose} key="cancel">
               取消
            </div>,
            <div className="color-main" onClick={handleOk} key="sure">
               确定
            </div>
         ]}
      />
   );
};

export default Modal;
